const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Webpack = require('webpack');

module.exports = {
  mode: 'production',
  entry: {
    index: path.resolve(__dirname, 'src/index.js'),
    other: path.resolve(__dirname, 'src/other.js')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: "[name].js",
  },
  devServer: {
    port: 3000,
    contentBase: path.join(__dirname, 'dist'),
    progress: true,
    compress: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src/index.html'),
      filename: 'index.html',
      minify: false
    })
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-react'
            ],
            plugins: [
              ["@babel/plugin-proposal-decorators", { "legacy": true }],
              ["@babel/plugin-proposal-class-properties"],
              ["@babel/plugin-transform-runtime"],
              ["@babel/plugin-transform-modules-commonjs"]
            ]
          }
        },
        // 只去查找哪些库
        include: path.resolve(__dirname,'src'),
        // 不去查找相关目录
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          "postcss-loader",
        ]
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          'style-loader',
          'css-loader',
          "sass-loader"
        ]
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            // 不会发起http请求,但是file-loader会发起http请求
            loader: 'url-loader',
            options: {
              limit: 200*1204,
              // 超过限制才会输出到指定目录
              outputPath: '/img/',
            }
          },
        ],
      }
    ]
  },
  optimization: {
    splitChunks: { // 分割代码块儿
      cacheGroups: { // 缓存组
        commons: { // 公共模块
          // name(module, chunks, cacheGroupKey) {
          //   const moduleFileName = module
          //     .identifier()
          //     .split('/')
          //     .reduceRight((item) => item)
          //     .split('.')[0];
          //   const allChunksNames = chunks.map((item) => item.name).join('~');
          //   return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
          // },
          name: 'commons',
          chunks: 'initial',
          minSize: 0,
          minChunks: 2,
        },
        // 抽离公共的第三方模块
        defaultVendors: {
          priority: 1,
          test: /node_modules/,
          name: 'vendor',
          chunks: 'initial',
          minSize: 0,
          minChunks: 2
        },
      }
    }
  }
}